<template>
  <div>
    <!-- 面包屑区域-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      <el-breadcrumb-item>用户详情</el-breadcrumb-item>
    </el-breadcrumb>

    <div>
      <el-card>
        <!-- 搜索和添加区域 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              placeholder="请输入内容"
              v-model="queryInfo.query"
              clearable
              @clear="getUsersList"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getUsersList"
              ></el-button>
            </el-input>
          </el-col>
          <el-col :span="3">
            <el-button type="primary" @click="addDialogVisible = true">
              添加用户
            </el-button>
          </el-col>
        </el-row>
        <!-- 用户数据展示和操作区域 -->
        <div>
          <el-table
            :data="usersInfoList"
            :border="true"
            style="width: 100%"
            stripe
          >
            <el-table-column type="index" label="#" width="180">
            </el-table-column>
            <el-table-column prop="username" label="姓名" width="180">
            </el-table-column>
            <el-table-column prop="mobile" label="电话号码" width="180">
            </el-table-column>
            <el-table-column prop="email" label="邮箱"> </el-table-column>
            <el-table-column label="状态">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.mg_state"
                  active-color="#409eff"
                  inactive-color="#dcdfe6"
                  @change="changUserState(scope.row)"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  round
                  size="mini"
                  @click="showEditDialog(scope.row.id)"
                ></el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  round
                  size="mini"
                  @click="removeUserById(scope.row.id)"
                ></el-button>
                <el-tooltip
                  content="角色分配"
                  placement="top"
                  :enterable="false"
                >
                  <el-button
                    type="warning"
                    icon="el-icon-setting"
                    round
                    size="mini"
                    @click="setRoleDialog(scope.row)"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页区 -->
        <div>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="this.queryInfo.pagenum"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="this.queryInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="this.total"
          >
          </el-pagination>
        </div>
      </el-card>
    </div>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 对话框添加用户表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 对话框编辑用户表单 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名"  >
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
  title="角色分配"
  :visible.sync="setRoleDialogVisible"
  width="50%"
  >
  <p>当前用户：{{ this.userInfo.username }}</p>
  <p>当前角色：{{ this.userInfo.role_name
}}</p>
<p>
  <span>角色列表：</span>
  <el-select v-model="selectRoleId" placeholder="请选择">
    <el-option
      v-for="item in RoleInfo"
      :key="item.id"
      :label="item.roleName"
      :value="item.id"
     >
    </el-option>
  </el-select>
  
</p>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="savaRoleInfo">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义邮箱校验规则
    var emailCheck = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail =
        /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
      if (regEmail.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的邮箱"));
    };
    // 自定义电话校验规则
    var mobileCheck = (rule, value, cb) => {
      // 验证电话的正则表达式
      const regMobile = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的电话"));
    };
    return {
      // 获取用户数据的接口参数
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      // 用户数据
      usersInfoList: [],
      total: 0,
      // 添加用户对话框
      addDialogVisible: false,
      // 表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 设置表单验证规则对象
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名的长度在3~10个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "用户名的长度在6~15个字符之间",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          // 自定义校验规则的校验 validator——验证器
          { validator: emailCheck, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: mobileCheck, trigger: "blur" },
        ],
      },
      // 编辑用户对话框
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          // 自定义校验规则的校验 validator——验证器
          { validator: emailCheck, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: mobileCheck, trigger: "blur" },
        ],
      },
      setRoleDialogVisible:false,
      // 当前用户信息
      userInfo:[],
      // 角色信息
     RoleInfo:[],
    //  选中的角色Id
     selectRoleId:''

    };
  },
  created() {
    this.getUsersList();
  },
  methods: {
    // 获取用户数据
    async getUsersList() {
      const { data: res } = await this.$axios.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status != 200) {
        return this.$message.error("获取数据失败");
      }
      this.usersInfoList = res.data.users;
      this.total = res.data.total;
    },
    // 监听分页的页大小改变
    handleSizeChange(newPageSize) {
      this.queryInfo.pagesize = newPageSize;
      this.getUsersList();
    },
    // 监听页码改变
    handleCurrentChange(newPageNum) {
      this.queryInfo.pagenum = newPageNum;
      this.getUsersList();
    },
    async changUserState(newUerinfo) {
      const { data: res } = await this.$axios.put(
        `users/${newUerinfo.id}/state/${newUerinfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        newUerinfo.mg_state = !newUerinfo.mg_state;
        return this.$message.error("更新状态失败");
      }
      this.$message.success("更新状态成功");
    },
    // 关闭对话框重置表单数据
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 确定添加用户、
    addUser() {
      this.$refs.addFormRef.validate(async (vaild) => {
        if (!vaild) return;
        // 发起添加用户的网络请求
        const { data: res } = await this.$axios.post("users", this.addForm);
        if (res.meta.status !== 200)  this.$message.error("添加用户失败！");
        
        this.$message.success("添加用户成功！")  
        this.addDialogVisible = false;
        this.getUsersList();
      });
    },
    // 监听编辑显示对话框
  async  showEditDialog(id){
     const{data:res}= await this.$axios.get('users/'+id)
     this.editForm=res.data
    //  console.log(this.editForm);
     this.editDialogVisible=true
    

    },
    // 关闭编辑对话框,重置验证
    editDialogClosed(){
      this.$refs.editFormRef.resetFields();
    },
    // 提交修改内容
    saveEdit(){
      this.$refs.editFormRef.validate(async vaild=>{
        if (!vaild) return;
      const{data:res} = await this.$axios.put('users/'+this.editForm.id,{
          email:this.editForm.email,
          mobile:this.editForm.mobile
        })
        if (res.meta.status !== 200) {
          this.$message.error("更新用户失败！");
        }
        this.$message.success("更新用户成功！");
        this.editDialogVisible = false;
        this.getUsersList();
      })

    },
    // 删除用户
   async removeUserById(id){
      // 询问是否继续删除用户
     const confirmResult= await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)

        if(confirmResult!=="confirm"){
          this.$message.info('已取消删除操作')
        }else{
            // 确认发起删除请求
      const{data:res} =await this.$axios.delete('users/'+id)
      if(res.meta.status!==200){
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('删除用户成功')
      this.getUsersList()
        }
      

    },
    // 点击分配角色
   async setRoleDialog(role){
      this.setRoleDialogVisible=true
      this.userInfo=role
     const{data:res}=await this.$axios.get('roles')
     this.RoleInfo=res.data

    },
   async savaRoleInfo(){
      if(!this.selectRoleId){
        return this.$message.info('还未选择分配角色')
      }
    const{data:res}= await  this.$axios.put(`users/${this.userInfo.id}/role`,{rid:this.selectRoleId})

    if(res.meta.status!==200){
      return this.$message.error(res.meta.msg)
      
    }
    this.$message.success('角色分配成功！')
    this.setRoleDialogVisible=false
    this.selectRoleId=''
    this.userInfo=[]

    }
  
  },
};
</script>

<style></style>
